'use strict';
layui.define('jquery', function(exports){
	let $ = layui.jquery;

	let obj = {
		articleId:'',
		btn:null,
		num:null,
		addUrl:'',
		delUrl:'',

		likeClass : '',
		unlikeClass:'',

		flag : true,


		//初始化
		init:function(obj){
			this.articleId = obj.articleId;
			this.btn = $(obj.btn);
			this.num = $(obj.num);
			this.addUrl = obj.addUrl;
			this.delUrl = obj.delUrl;

			this.likeClass = obj.likeClass;
			this.unlikeClass = obj.unlikeClass;


			this.event();
		},

		//绑定事件
		event:function(){
			let that = this;

			//添加收藏
			this.btn.on('click', function(){
				let del = $(this).hasClass(that.likeClass),
					add = $(this).hasClass(that.unlikeClass);

				if( !that.flag )
					return;
				that.flag = false;
				that.request(this, {article_id:that.articleId, add: add});
			})
		},
		//发送请求
		request: function(el, data){
			let that = this
				,url = that.addUrl;

			if(!data.add){
				url = that.delUrl;
			}

			//请求
			$.ajax({
				url: url,
				type: 'POST',
				data: data,
				success : function(d){
					layer.msg(d.msg, function(){
						if(d.code === 0){
							if(data.add) {
								$(el).removeClass(that.unlikeClass).addClass(that.likeClass);
								$(that.num).text(parseInt($(that.num).text()) + 1);
							} else {
								$(el).removeClass(that.likeClass).addClass(that.unlikeClass);
								$(that.num).text(parseInt($(that.num).text()) - 1);
							}
						}
						console.log(d);
						that.flag = true;
					});

				}
			});
		}
	};
  
  //输出test接口
  exports('like', obj);
}); 